package com.wteam.dragon.system.apps.security.service;

import com.wteam.dragon.model.pojo.dto.UserDto;
import com.wteam.dragon.model.service.RoleService;
import com.wteam.dragon.model.service.UserService;
import com.wteam.dragon.system.apps.security.service.deo.JwtUserDto;
import com.wteam.dragon.system.exception.BadRequestException;
import com.wteam.dragon.system.exception.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author 陈晓辉
 * @Date 2020/4/2 10:57
 */
@Service("userDetailsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@RequiredArgsConstructor
public class DetailsServiceImpl implements UserDetailsService {
    private final UserService userService;
    private final RoleService roleService;

    @Override
    public JwtUserDto loadUserByUsername(String username) {
        UserDto user;
        try {
            user = userService.findByName(username);
        } catch (EntityNotFoundException e) {
            // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
            throw new UsernameNotFoundException("找不到该用户", e);
        }
        if (user == null) {
            throw new UsernameNotFoundException("找不到该用户");
        } else {
            if (!user.getEnabled()) {
                throw new BadRequestException("账号未激活");
            }
            return new JwtUserDto(
                    user,
                    roleService.mapToGrantedAuthorities(user)
            );
        }
    }
}
